import { ConfigProvider, message } from 'antd';
import { FC } from 'react';

import { get } from '@/api';
import { GraphContainer } from '@/components/complex/GraphContainer';
import { NodesPanel } from '@/components/complex/NodesPanel';
import { useDictStore } from '@/store/dict';
import { useNodeResults } from '@/store/node-results';
import { useNodeVerificationResults } from '@/store/node-verification';
import { getGraphJsonFromStorage } from '@/utils/graph';

import { FlowActions } from '../Actions';

export const FlowContent: FC = memo(() => {
  const { fetchDictData } = useDictStore();
  const [searchParams] = useSearchParams();
  const [storageGraphJson, setStorageGraphJson] = useState<any>(null);
  const flowId = searchParams.get('flowId') as any;
  const { clearResults, hasExecResult } = useNodeResults();
  const nodeVerificationResult = useNodeVerificationResults();
  const [messageApi, contextHolder] = message.useMessage();

  useEffect(() => {
    fetchDictData();
  }, [fetchDictData]);

  useEffect(() => {
    if (flowId) {
      const json = getGraphJsonFromStorage(flowId);
      if (!json) {
        messageApi.open({
          type: 'loading',
          content: '正在为您加载图表',
          duration: 0
        });
        get('/flow/get', { flowId })
          .then((res) => {
            setStorageGraphJson(res.graph ? JSON.parse(res.graph) : null);
          })
          .finally(() => {
            setTimeout(() => {
              messageApi.destroy();
              messageApi.success({
                content: '加载成功'
              });
            }, 800);
          });
      } else {
        setStorageGraphJson(json);
      }
    }
  }, [flowId, messageApi, searchParams]);

  useEffect(() => {
    clearResults();
    nodeVerificationResult.clearResults();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [flowId]);

  return (
    <div className="flow-content w-full h-full flex flex-col">
      {contextHolder}
      <ConfigProvider componentDisabled={hasExecResult}>
        <GraphContainer graphJson={storageGraphJson} mode="edit">
          <div className="flex flex-col">
            {flowId && <FlowActions onImportSuccess={setStorageGraphJson} />}
            <NodesPanel className="flex-1" />
          </div>
        </GraphContainer>
      </ConfigProvider>
    </div>
  );
});
